package com.qdlc.p2p.manage.action.additional;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;

import com.opensymphony.xwork2.ModelDriven;
import com.qdlc.p2p.biz.service.additional.CardRuleService;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.constant.CardRuleStatus;
import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.common.exception.BusinessException;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.dto.CardRule;
import com.qdlc.p2p.dal.dto.Operator;
import com.qdlc.p2p.dal.model.CardRuleModel;

/**
 * 管理卡片规则
 *
 * @author Kaiju Zhao
 * @version V1.0.0
 * @date 2016-05-06
 */
public class ManageCardRuleAction extends BaseAction<CardRuleModel> implements ModelDriven<CardRuleModel> {

    @Resource
    private CardRuleService cardRuleService;

    private CardRuleModel model = new CardRuleModel();

    public CardRuleModel getModel() {
        return model;
    }

    private Map<String, Object> data;

    /**
     * 进入卡片规则管理页面
     *
     * @author Kaiju Zhao
     */
    @Action("/modules/additional/card/cardRule/cardRuleManager")
    public String cardRuleManager() {
        return "cardRuleManager";
    }

    /**
     * 获取所有卡片规则列表
     *
     * @author Kaiju Zhao
     */
    @Action("/modules/additional/card/cardRule/cardRuleList")
    public void cardRuleList() throws IOException {
        // 初始化status值为99，表示查询所有
        String status = paramString("status");
        if (StringUtil.isBlank(status)) {
            model.setStatus(CardRuleStatus.STATUS_UNKNOWN);
        }
        data = new HashMap<String, Object>();
        PageDataList<CardRuleModel> pageDataList = cardRuleService.list(model);
        data.put("total", pageDataList.getPage().getTotal());
        data.put("rows", pageDataList.getList());
        printJson(getStringOfJpaObj(data));
    }

    /**
     * 进入添加卡片规则页面
     *
     * @return
     * @author Kaiju Zhao
     */
    @Action("/modules/additional/card/cardRule/cardRuleAddPage")
    public String cardRuleAddPage() {
        return "cardRuleAddPage";
    }

    /**
     * 添加卡片规则
     *
     * @return
     * @throws Exception
     * @author Kaiju Zhao
     */
    @Action("/modules/additional/card/cardRule/cardRuleAdd")
    public void cardRuleAdd() throws Exception {
        Operator operator = getOperator();
        if (null == operator) {
            printResult("请先登录！", false);
            return;
        }
        checkCardRuleModel(model);
        model.setAddTime(DateUtil.getNow());
        model.setAddIp(Global.getIP());
        CardRule cardRule = cardRuleService.saveCardRule(model);
        if (null == cardRule) {
            printResult("添加卡片规则失败！", false);
            return;
        }
        printResult("添加卡片规则成功！", true);
    }

    /**
     * 修改卡片规则页面
     *
     * @return
     * @throws Exception
     * @author Kaiju Zhao
     */
    @Action("/modules/additional/card/cardRule/cardRuleEditPage")
    public String cardRuleEditPage() throws Exception {
        CardRuleModel cardRule = cardRuleService.findCardRuleById(model.getId());
        if (null == cardRule) {
            printResult("该卡片规则不存在!", false);
            return "cardRuleManager";
        }
        request.setAttribute("cardRule", cardRule);
        return "cardRuleEditPage";
    }

    /**
     * 修改卡片规则
     *
     * @return
     * @throws Exception
     * @author Kaiju Zhao
     */
    @Action("/modules/additional/card/cardRule/cardRuleEdit")
    public void cardRuleEdit() throws Exception {
        Operator operator = getOperator();
        if (null == operator) {
            printResult("请先登录！", false);
            return;
        }
        checkCardRuleModel(model);
        CardRuleModel cardRuleModel = cardRuleService.findCardRuleById(model.getId());
        if (null == cardRuleModel) {
            printResult("该卡片规则不存在，修改卡片规则失败！", false);
            return;
        }
        CardRule cardRule = CardRuleModel.prototype(model);
        cardRuleService.updateCardRule(cardRule);
        printResult("修改卡片规则成功！", true);
    }

    /**
     * 查看卡片规则详情页面
     *
     * @return
     * @throws Exception
     * @author Kaiju Zhao
     */
    @Action("/modules/additional/card/cardRule/cardRuleDetailPage")
    public String cardRuleDetailPage() throws Exception {
        CardRuleModel cardRule = cardRuleService.findCardRuleById(model.getId());
        if (null == cardRule) {
            printResult("该卡片规则不存在!", false);
            return "cardRuleManager";
        }
        request.setAttribute("cardRule", cardRule);
        return "cardRuleDetailPage";
    }

    /**
     * 将卡片规则标记为启用
     *
     * @return
     * @throws IOException
     * @author Kaiju Zhao
     */
    @Action("/modules/additional/card/cardRule/cardRuleEnable")
    public void cardRuleEnable() throws Exception {
        Operator operator = getOperator();
        if (null == operator) {
            printResult("请先登录！", false);
            return;
        }
        long cardRuleId = model.getId();
        CardRuleModel cardRuleModel = cardRuleService.findCardRuleById(cardRuleId);
        if (null == cardRuleModel) {
            printResult("该卡片规则不存在，启用卡片规则失败！", false);
            return;
        }
        model.setType(cardRuleModel.getType());
        model.setStatus(CardRuleStatus.STATUS_ENABLE);
        checkCardRuleModel(model);
        int result = cardRuleService.updateCardRuleStatus(CardRuleStatus.STATUS_ENABLE,
                CardRuleStatus.STATUS_DISABLE, cardRuleId);
        if (result > 0) {
            printWebSuccess();
        } else {
            printWebResult("将卡片规则标记为启用失败，请确认卡片规则是否已是启用状态！", false);
        }
    }

    /**
     * 将卡片规则标记为禁用
     *
     * @return
     * @throws IOException
     * @author Kaiju Zhao
     */
    @Action("/modules/additional/card/cardRule/cardRuleDisable")
    public void cardRuleDisable() throws Exception {
        Operator operator = getOperator();
        if (null == operator) {
            printResult("请先登录！", false);
            return;
        }
        long cardRuleId = model.getId();
        CardRuleModel cardRuleModel = cardRuleService.findCardRuleById(cardRuleId);
        if (null == cardRuleModel) {
            printResult("该卡片规则不存在，禁用卡片规则失败！", false);
            return;
        }
        model.setType(cardRuleModel.getType());
        model.setStatus(CardRuleStatus.STATUS_DISABLE);
        checkCardRuleModel(model);
        int result = cardRuleService.updateCardRuleStatus(CardRuleStatus.STATUS_DISABLE,
                CardRuleStatus.STATUS_ENABLE, cardRuleId);
        if (result > 0) {
            printWebSuccess();
        } else {
            printWebResult("将卡片规则标记为禁用失败，请确认卡片规则是否已是禁用状态！", false);
        }
    }

    /**
     * 校验卡片规则
     *
     * @param model
     * @author Kaiju Zhao
     */
    private void checkCardRuleModel(CardRuleModel model) throws Exception {
        if (null == model) {
            throw new BusinessException("设置卡片规则模型为空!", BusinessException.TYPE_JSON);
        }

        int status = model.getStatus();
        if (CardRuleStatus.STATUS_ENABLE != status
                && CardRuleStatus.STATUS_DISABLE != status
                && CardRuleStatus.STATUS_UNKNOWN != status) {
            throw new BusinessException("设置卡片规则状态不合法!", BusinessException.TYPE_JSON);
        }

        // 判断是否存在该卡片规则（平台只存在一个类型和状态相同的卡片规则）
        if (CardRuleStatus.STATUS_ENABLE == status) {
            int existNum = cardRuleService.existCardRule(model.getId(), model.getType(), status);
            if (existNum > 0) {
                throw new BusinessException("系统只能启用一种该类型的卡片规则!", BusinessException.TYPE_JSON);
            }
        }
    }

}